import React, { useEffect, useState } from 'react'
import { Card, Form, Button, Input, Select, Table, Row, Col, Tooltip, message } from 'antd'
import { SearchOutlined } from "@ant-design/icons"
import { useNavigate } from 'react-router-dom'


import {
  getHospitalListRequest,             //获取医院列表请求
  getProvinceRequest,                 //请求省份
  getCityOrblockRequest,              //请求市或区
  hospitalCheckedStatusRequest,       //切换上下线请求
} from "@api/hospital/hospitalList"

import type {
  getHosListSearchParamsType,         //获取医院列表请求参数中searchParams的类型
  hosListContentType,                 //返回的数据中数组的类型
  hospitalListItemsType,              //content数组中 每一条数据的类型
  getThreeReturnType,              //请求省份的返回值类型
} from "@api/hospital/model/hospitalListTypes"


export default function HospitalList() {
  const navigate = useNavigate()

  //控制表格loding动画
  const [isLoading, setIsLoading] = useState(false)
  //控制当前页码
  const [page, setCurrent] = useState(1)
  //控制每页条数   
  const [limit, setPageSize] = useState(10)
  //保存数据总条数
  const [total, setTotal] = useState(0)
  //保存表单数据
  const [searchParams, setSearchParams] = useState<getHosListSearchParamsType>({})
  //保存医院列表数据
  const [hospitalList, setHospitalList] = useState<hosListContentType>([])
  //保存省份数据 
  const [province, setProvince] = useState<getThreeReturnType>([])
  //保存市数据 
  const [city, setCity] = useState<getThreeReturnType>([])
  //保存区数据 
  const [block, setBlock] = useState<getThreeReturnType>([])
  //保存医院类型
  const [hospitalType, setHospitalType] = useState<getThreeReturnType>([])
  //保存状态上下线成功重新渲染
  const [changeStatus , setChangeStatus] = useState(true)



  //拿到表单实例
  const [form] = Form.useForm()


  //1.刚进页面请求医院列表
  useEffect(() => {
    (async () => {
      //loading效果
      setIsLoading(true)

      //发送获取医院列表请求
      const re = await getHospitalListRequest(page, limit, searchParams)

      //改变数组渲染页面
      setHospitalList(re.content)
      //渲染数据总条数
      setTotal(re.totalElements)

      //loading效果
      setIsLoading(false)

    })()
  }, [searchParams, page, limit , changeStatus])


  //2.刚进页面请求省份
  useEffect(() => {
    (async () => {
      const result = await getProvinceRequest()
      //把请求省份回来的数组保存到状态
      setProvince(result)

    })()
  }, [])

  //3.刚进页面请求医院类型
  useEffect(() => {
    (async () => {
      const result = await getCityOrblockRequest("10000"); //发送10000固定获取医院类型
      //把查询到的医院类型设置到状态
      setHospitalType(result)

    })()
  }, [])


  
  //表格中列数据的配置
  const columns = [
    {
      title: '序号',
      width: 60,
      dataIndex: 'index',
      align: "center" as "center", //文本居中
      render(_: any, __: any, index: number) {
        return index + 1
      }
    },
    {
      title: '医院logo',
      align: "center" as "center", //文本居中
      render(_: any, data: hospitalListItemsType) {
        return <img width={100} src={`data:image/jpeg;base64,${data.logoData}`} alt="" />
      }
    },
    {
      title: '医院名称',
      dataIndex: 'hosname',
      align: "center" as "center", //文本居中
    },
    {
      title: '等级',
      align: "center" as "center", //文本居中
      render(_: any, data: hospitalListItemsType) {
        return data.param.hostypeString
      }
    },
    {
      title: '详细地址',
      align: "center" as "center", //文本居中
      render(_: any, data: hospitalListItemsType) {
        return data.param.fullAddress
      }
    },
    {
      title: '状态',
      align: "center" as "center", //文本居中
      render(_: any, data: hospitalListItemsType) {
        return data.status === 0 ? "下线" : "上线"
      }
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      align: "center" as "center", //文本居中
    },
    {
      title: '操作',
      width: 240,
      fixed: "right" as "right",
      dataIndex: "do",
      align: "center" as "center", //文本居中
      render(_: any, data: hospitalListItemsType) {
        //拿到当前数据对应的id 发送查看医院请求
        const { id } = data
        //dang拿到当前数据对应的status  //发送上下线请求
        const {status}  =data
        //拿到当前数据对应的hoscode    //发送排班请求
        const {hoscode} = data

        return (
          <div>
            <Tooltip title={"查看"}>
              <Button type='primary' onClick={goSearchHandle(id)}>查看</Button>
            </Tooltip>

            <Tooltip title={"排班"}>
              <Button type='primary' onClick={goHosSechedule(hoscode)}>排班</Button>
            </Tooltip>

            <Tooltip title={  status === 0 ? "上线" : "下线"  }>
              <Button type='primary' onClick = {changeStatusHandle(id , status === 0 ? 1 : 0)}>
                {  status === 0 ? "上线" : "下线"  }
              </Button>
            </Tooltip>
          </div >
        )
      }
    }
  ];



  //1.点击省份获取市的回调函数
  const getCityHandle = async (value: string) => {
    //请求市
    const result = await getCityOrblockRequest(value)
    //把请求到的数据放到状态中
    setCity(result)

    //再次点击省的时候把市和区的输入框内容清空
    form.setFieldsValue({ cityCode: null, districtCode: null })
    //并且把区中的数据也要清空
    setBlock([])

  }

  //2.点击市获取区的回调函数
  const getBlockHandle = async (value: string) => {
    //请求区
    const result = await getCityOrblockRequest(value)
    //把请求到的数据放到状态中
    setBlock(result)

    //再次点击市清除区的输入框内容
    form.setFieldsValue({ districtCode: null });

  }

  //3.点击查询的回调函数
  const searchHandle = (searchParams: getHosListSearchParamsType) => {
    //点击查询根据key value 收集表单数据 改变状态查询渲染
    setSearchParams(searchParams)
  }

  //4.点击清空的回调函数
  const clearHandle = () => {
    //修改表单状态为空查询渲染
    setSearchParams({})
  }

  //5.点击查看的回调函数
  const goSearchHandle = (id: string) => {
    return () => {
      //点击查看带着当前这条数据的id通过params传参去医院详情页面
      navigate(`/syt/hospatil/hospitalshow/${id}` , {
        //测试自己封装的Hook
        state: {
          a: 666
        }
      })
    }
  }

  //6.点击上下线的回调函数
  const changeStatusHandle = (id:string , status: 0 | 1) => {
    //如果点的是上线就期望下线 发送1 下线发送0
    return async () => {
      await hospitalCheckedStatusRequest(id , status);

      //成功提示
      if(status === 1){
        message.success("上线成功!")
      } else {
        message.success("下线成功!")
      }
      
      
      //重新渲染
      setChangeStatus(!changeStatus);

    }
  }

  //7.点击排班的回调函数
  const goHosSechedule = (hoscode:string) => {
    return () => {
      //带着当前数据的医院编号去医院排班页面
      navigate(`/syt/hospatil/hospitalschedule/${hoscode}`)
    }
  }


  return (
    <div>
      <Card>

        <Form
          name="basic"
          form={form} //创建表单实例
          onFinish={searchHandle} //表单提交事件
        >

          {/* 第一行 列间距10 */}
          <Row gutter={10}>
            <Col span={4}>
              <Form.Item
                name="provinceCode"
              >
                <Select
                  placeholder="请输入省份"
                  allowClear
                  onChange={getCityHandle}
                >
                  {
                    province.map((item) => {
                      return <Select.Option value={item.id} key={item.id}>{item.name}</Select.Option>
                    })
                  }
                </Select>
              </Form.Item>
            </Col>

            <Col span={4}>
              <Form.Item
                name="cityCode"
              >
                <Select
                  placeholder="请输入市"
                  allowClear
                  onChange={getBlockHandle}
                >
                  {
                    city.map((item) => {
                      return <Select.Option value={item.id} key={item.id}>{item.name}</Select.Option>
                    })
                  }
                </Select>
              </Form.Item>
            </Col>

            <Col span={4}>
              <Form.Item
                name="districtCode"
              >
                <Select
                  placeholder="请输入县/区"
                  allowClear
                >
                  {
                    block.map((item) => {
                      return <Select.Option value={item.id} key={item.id}>{item.name}</Select.Option>
                    })
                  }
                </Select>
              </Form.Item>
            </Col>

            <Col span={4}>
              <Form.Item
                name="hosname"
              >
                <Input placeholder="医院名称" />
              </Form.Item>
            </Col>

            <Col span={4}>
              <Form.Item
                name="hoscode"
              >
                <Input placeholder='医院编号' />
              </Form.Item>
            </Col>

            <Col span={4}>
              <Form.Item name="hostype" >
                <Select
                  placeholder="医院类型"
                  allowClear
                >
                  {
                    hospitalType.map((item) => {
                      return <Select.Option value={item.value} key={item.id}>{item.name}</Select.Option>
                    })
                  }
                </Select>
              </Form.Item>
            </Col>
          </Row>


          {/* 第二行 列间距10 */}
          <Row gutter={10}>
            <Col span={4}>
              <Form.Item
                name="status"
              >
                <Select
                  placeholder="医院状态"
                  allowClear
                >
                  <Select.Option value={1}>上线</Select.Option>
                  <Select.Option value={0}>下线</Select.Option>
                </Select>
              </Form.Item>
            </Col>

            <Col span={2}>
              <Form.Item >
                <Button type="primary" htmlType="submit" icon={<SearchOutlined />} >
                  查询
                </Button>
              </Form.Item>
            </Col>

            <Col span={2}>
              <Form.Item>
                <Button type="default" htmlType="reset" onClick={clearHandle}>
                  清空
                </Button>
              </Form.Item>
            </Col>

          </Row>

        </Form>


        <Table
          style={{ marginTop: "30px" }}
          columns={columns}
          dataSource={hospitalList}
          scroll={{ x: 1100 }}
          bordered
          //在table中 要求dataSource中有key属性,但是如果真的没有key 则可以使用rowKey属性指定dataSource中的一个属性作为Key
          rowKey="id"

          //表格加载时的等待动画
          loading={isLoading}

          //分页器
          pagination={{
            //页码的配置：当前页码
            current: page,
            //每页条数
            pageSize: limit,
            //总数据的数量
            total: total,
            //展示更改每页条数的选项(默认total大于50条的时候开启)
            pageSizeOptions: [1, 2, 3, 4, 5, 6, 7, 8, 9],
            //是否直接开启更新每页条数的选项
            showSizeChanger: true,

            //展示总数据
            showTotal(total) {
              return `总共有${total}条数据`
            },

            onChange(page: number, pageSize: number) {
              setCurrent(page)
              setPageSize(pageSize)
            }

          }}
        />

      </Card>
    </div >
  )
}
